package com.way.upload.frontend.controllers;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * Controller层
 */
@Controller
public class UploadController {
	private static Logger log = Logger.getLogger(UploadController.class);
	
	@RequestMapping("/")
	public String sample() {
		return "sample";
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
			@RequestParam("file") MultipartFile file) {
		if (!file.isEmpty()) {
			try {
				byte[] bytes = file.getBytes();
				File lfile = new File(file.getName());
				BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(lfile));
				stream.write(bytes);
				stream.close();
				return lfile.getAbsolutePath();
			} catch (Exception e) {
				log.error(e);
				return null;
			}
		} else {
			log.info("empty file");
			return null;
		}
	}
}
